package com.yuanqi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.dto.SalesOrderDTO;
import com.yuanqi.dto.SalesOrderListDTO;
import com.yuanqi.dto.SalesOrderQueryDTO;
import com.yuanqi.pojo.SalesOrder;
import com.yuanqi.service.SalesOrderService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.Map;

@RestController
@RequestMapping("/api/sales/order")
public class SalesOrderController {

    @Resource
    private SalesOrderService salesOrderService;



    /** 创建完整销售订单（包含明细） */
    @PostMapping("/full")
    public Map<String,Object> createFullOrder(@RequestBody SalesOrderDTO salesOrderDTO){
        try {
            SalesOrderDTO result = salesOrderService.createOrUpdateOrder(salesOrderDTO);
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", true);
            resp.put("data", result);
            resp.put("message", "订单创建成功");
            return resp;
        } catch (Exception e) {
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "订单创建失败：" + e.getMessage());
            return resp;
        }
    }

    /** 更新完整销售订单（包含明细） */
    @PutMapping("/full/{id}")
    public Map<String,Object> updateFullOrder(@PathVariable Long id, @RequestBody SalesOrderDTO salesOrderDTO){
        try {
            salesOrderDTO.getOrder().setId(id);
            SalesOrderDTO result = salesOrderService.createOrUpdateOrder(salesOrderDTO);
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", true);
            resp.put("data", result);
            resp.put("message", "订单更新成功");
            return resp;
        } catch (Exception e) {
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "订单更新失败：" + e.getMessage());
        return resp;
        }
    }

    /** 基础查询：支持单号、客户名(需前端传入客户Id或改联合查询)、日期区间 */
    @GetMapping("/page")
    public Page<SalesOrder> page(@RequestParam(defaultValue = "1") Long pageNo,
                                 @RequestParam(defaultValue = "10") Long pageSize,
                                 @RequestParam(required = false) String soCode,
                                 @RequestParam(required = false) Long customerId,
                                 @RequestParam(required = false) String startDate,
                                 @RequestParam(required = false) String endDate){
        LambdaQueryWrapper<SalesOrder> qw = new LambdaQueryWrapper<>();
        if(soCode!=null && !soCode.isEmpty()) qw.like(SalesOrder::getSoCode, soCode);
        if(customerId!=null) qw.eq(SalesOrder::getCustomerId, customerId);
        if(startDate!=null && !startDate.isEmpty()) qw.ge(SalesOrder::getCreatedAt, java.sql.Date.valueOf(LocalDate.parse(startDate)));
        if(endDate!=null && !endDate.isEmpty()) qw.le(SalesOrder::getCreatedAt, java.sql.Date.valueOf(LocalDate.parse(endDate)));
        qw.orderByDesc(SalesOrder::getCreatedAt);
        return salesOrderService.page(new Page<>(pageNo,pageSize), qw);
    }

    /** 高级分页查询 */
    @PostMapping("/page/advanced")
    public IPage<SalesOrderDTO> advancedPage(@RequestBody SalesOrderQueryDTO queryDTO){
        return salesOrderService.pageSalesOrders(queryDTO);
    }

    /** 查询订单列表（用于前端列表显示） */
    @GetMapping("/list")
    public Map<String, Object> getOrderList(@RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize,
                                           @RequestParam(required = false) String keyword) {
        try {
            IPage<SalesOrderListDTO> result = salesOrderService.getOrderListPage(pageNum, pageSize, keyword);
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", true);
            resp.put("data", result);
            resp.put("message", "查询成功");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "查询失败：" + e.getMessage());
            return resp;
        }
    }

    /** 查询所有订单列表（用于前端列表显示） */
    @GetMapping("/list/all")
    public Map<String, Object> getAllOrderList() {
        try {
            List<SalesOrderListDTO> result = salesOrderService.getAllOrderList();
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", true);
            resp.put("data", result);
            resp.put("message", "查询成功");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "查询失败：" + e.getMessage());
            return resp;
        }
    }

    /** 搜索订单（用于退货订单选择原订单） */
    @GetMapping("/search")
    public Map<String, Object> searchOrders(@RequestParam(required = false) String keyword,
                                           @RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            // 只查询已完成的订单（状态为2），用于退货
            IPage<SalesOrderListDTO> result = salesOrderService.getOrderListPage(pageNum, pageSize, keyword);
            
            // 过滤出已完成的订单
            List<SalesOrderListDTO> completedOrders = result.getRecords().stream()
                .filter(order -> order.getStatus() == 2) // 状态2表示已完成
                .collect(java.util.stream.Collectors.toList());
            
            // 创建新的分页结果
            IPage<SalesOrderListDTO> filteredResult = new Page<>(pageNum, pageSize);
            filteredResult.setRecords(completedOrders);
            filteredResult.setTotal(completedOrders.size());
            filteredResult.setCurrent(pageNum);
            filteredResult.setSize(pageSize);
            
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", true);
            resp.put("data", filteredResult);
            resp.put("message", "查询成功");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "查询失败：" + e.getMessage());
            return resp;
        }
    }

    /** 搜索商品（用于退货订单选择商品） */
    @GetMapping("/products/search")
    public Map<String, Object> searchProducts(@RequestParam(required = false) String keyword,
                                             @RequestParam(defaultValue = "1") Integer pageNo,
                                             @RequestParam(defaultValue = "20") Integer pageSize) {
        try {
            // 使用MyBatis查询商品
            List<Map<String, Object>> products = salesOrderService.searchProducts(keyword, pageNo, pageSize);
            Long total = salesOrderService.countProducts(keyword);
            
            // 构建分页结果
            Page<Map<String, Object>> page = new Page<>(pageNo, pageSize);
            page.setRecords(products);
            page.setTotal(total);
            
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", true);
            resp.put("data", page);
            resp.put("message", "查询成功");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "查询失败：" + e.getMessage());
            return resp;
        }
    }

    /** 根据订单ID查询客户名称 */
    @GetMapping("/customer-by-order/{orderId}")
    public Map<String, Object> getCustomerNameByOrderId(@PathVariable Long orderId) {
        try {
            String customerName = salesOrderService.getCustomerNameByOrderId(orderId);
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", true);
            resp.put("data", customerName);
            resp.put("message", "查询成功");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "查询失败：" + e.getMessage());
            return resp;
        }
    }

    /** 根据订单ID查询订单信息（包含客户名称） */
    @GetMapping("/info/{orderId}")
    public Map<String, Object> getOrderInfoById(@PathVariable Long orderId) {
        try {
            Map<String, Object> orderInfo = salesOrderService.getOrderInfoById(orderId);
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", true);
            resp.put("data", orderInfo);
            resp.put("message", "查询成功");
            return resp;
        } catch (Exception e) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "查询失败：" + e.getMessage());
            return resp;
        }
    }

    /** 删除/批量删除：仅未提交(0)允许删除 */
    @DeleteMapping("/batch/order")
    public Map<String,Object> deleteBatch(@RequestParam("ids") List<Long> ids){
        LambdaQueryWrapper<SalesOrder> qw = new LambdaQueryWrapper<>();
        qw.in(SalesOrder::getId, ids).eq(SalesOrder::getStatus, 0);
        List<SalesOrder> toDelete = salesOrderService.list(qw);
        int can = toDelete.size();
        boolean ok = can>0 && salesOrderService.removeBatchByIds(toDelete);
        Map<String,Object> resp=new HashMap<>();
        resp.put("success", ok);
        resp.put("deleted", ok?can:0);
        resp.put("message", ok?"删除成功":"仅允许删除未提交的订单");
        return resp;
    }

    /** 编辑：仅未提交(0)或审核拒绝(3)可编辑 */
    @PutMapping("/{id}")
    public Map<String,Object> update(@PathVariable Long id, @RequestBody SalesOrder order){
        SalesOrder db = salesOrderService.getById(id);
        Map<String,Object> resp=new HashMap<>();
        if(db==null){ resp.put("success",false); resp.put("message","订单不存在"); return resp; }
        if(db.getStatus()!=0 && db.getStatus()!=3){
            resp.put("success",false); resp.put("message","仅未提交或审核拒绝的订单可编辑");
            return resp;
        }
        order.setId(id);
        order.setUpdatedAt(new Date());
        boolean ok = salesOrderService.updateById(order);
        resp.put("success", ok);
        resp.put("message", ok ? "订单更新成功" : "订单更新失败");
        return resp;
    }



    /** 查看完整订单详情（包含明细和客户信息） */
    @GetMapping("/{id}/full")
    public Map<String,Object> fullDetail(@PathVariable Long id){
        SalesOrderDTO dto = salesOrderService.getSalesOrderDetail(id);
        Map<String,Object> resp = new HashMap<>();
        if (dto != null) {
            resp.put("success", true);
            resp.put("data", dto);
        } else {
            resp.put("success", false);
            resp.put("message", "订单不存在");
        }
        return resp;
    }

    /** 提交订单审核 */
    @PostMapping("/{id}/submit")
    public Map<String,Object> submitOrder(@PathVariable Long id){
        try {
            boolean result = salesOrderService.submitForReview(id);
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "订单提交成功" : "订单提交失败");
            return resp;
        } catch (Exception e) {
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "订单提交失败：" + e.getMessage());
            return resp;
        }
    }

    /** 审核通过订单 */
    @PostMapping("/{id}/approve")
    public Map<String,Object> approveOrder(@PathVariable Long id, @RequestParam(required = false) String approvalRemark){
        try {
            boolean result = salesOrderService.approveOrder(id, approvalRemark);
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "订单审核通过" : "订单审核失败");
            return resp;
        } catch (Exception e) {
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "订单审核失败：" + e.getMessage());
            return resp;
        }
    }

    /** 拒绝订单 */
    @PostMapping("/{id}/reject")
    public Map<String,Object> rejectOrder(@PathVariable Long id, @RequestParam(required = false) String rejectReason){
        try {
            boolean result = salesOrderService.rejectOrder(id, rejectReason);
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "订单已拒绝" : "订单拒绝失败");
            return resp;
        } catch (Exception e) {
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "订单拒绝失败：" + e.getMessage());
            return resp;
        }
    }

    /** 关闭订单 */
    @PostMapping("/{id}/close")
    public Map<String,Object> closeOrder(@PathVariable Long id, @RequestParam(required = false) String closeReason){
        try {
            boolean result = salesOrderService.closeOrder(id, closeReason);
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "订单已关闭" : "订单关闭失败");
            return resp;
        } catch (Exception e) {
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "订单关闭失败：" + e.getMessage());
            return resp;
        }
    }

    /** 根据客户ID查询订单列表 */
    @GetMapping("/customer/{customerId}")
    public Map<String,Object> getOrdersByCustomer(@PathVariable Long customerId){
        List<SalesOrder> orders = salesOrderService.getOrdersByCustomerId(customerId);
        Map<String,Object> resp = new HashMap<>();
        resp.put("success", true);
        resp.put("data", orders);
        resp.put("total", orders.size());
        return resp;
    }

    /** 打印：返回PDF文件流 */
    @GetMapping("/{id}/print")
    public ResponseEntity<byte[]> printData(@PathVariable Long id){
        try {
            // 获取订单详情
            SalesOrder so = salesOrderService.getById(id);
            if (so == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 生成单个订单的PDF文件
            byte[] pdfBytes = salesOrderService.generateSingleOrderPDF(so);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData("attachment", "销售订单_" + (so.getSoCode() != null ? so.getSoCode() : so.getId()) + ".pdf");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(pdfBytes);
                    
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /** 批量打印：返回PDF文件流 */
    @PostMapping("/print/batch")
    public ResponseEntity<byte[]> printOrdersBatch(@RequestParam List<Long> ids) {
        try {
            // 获取所有订单的详细信息
            List<SalesOrder> orders = salesOrderService.listByIds(ids);
            if (orders.isEmpty()) {
                return ResponseEntity.notFound().build();
            }

            // 生成PDF文件
            byte[] pdfBytes = salesOrderService.generateBatchPrintPDF(orders);
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentDispositionFormData("attachment", "销售订单.pdf");
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(pdfBytes);
                    
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /** 获取订单状态统计 */
    @GetMapping("/stats")
    public Map<String,Object> getOrderStats(){
        Map<String,Object> resp = new HashMap<>();

        // 统计各状态订单数量
        LambdaQueryWrapper<SalesOrder> draftWrapper = new LambdaQueryWrapper<>();
        draftWrapper.eq(SalesOrder::getStatus, 0);
        long draftCount = salesOrderService.count(draftWrapper);

        LambdaQueryWrapper<SalesOrder> submittedWrapper = new LambdaQueryWrapper<>();
        submittedWrapper.eq(SalesOrder::getStatus, 1);
        long submittedCount = salesOrderService.count(submittedWrapper);

        LambdaQueryWrapper<SalesOrder> approvedWrapper = new LambdaQueryWrapper<>();
        approvedWrapper.eq(SalesOrder::getStatus, 2);
        long approvedCount = salesOrderService.count(approvedWrapper);

        LambdaQueryWrapper<SalesOrder> rejectedWrapper = new LambdaQueryWrapper<>();
        rejectedWrapper.eq(SalesOrder::getStatus, 3);
        long rejectedCount = salesOrderService.count(rejectedWrapper);

        LambdaQueryWrapper<SalesOrder> closedWrapper = new LambdaQueryWrapper<>();
        closedWrapper.eq(SalesOrder::getStatus, 4);
        long closedCount = salesOrderService.count(closedWrapper);

        resp.put("success", true);
        resp.put("draftCount", draftCount);
        resp.put("submittedCount", submittedCount);
        resp.put("approvedCount", approvedCount);
        resp.put("rejectedCount", rejectedCount);
        resp.put("closedCount", closedCount);
        resp.put("totalCount", draftCount + submittedCount + approvedCount + rejectedCount + closedCount);

        return resp;
    }

    /** 删除订单（支持单个和批量） */
    @DeleteMapping("/batch")
    public Map<String,Object> deleteOrderBatch(@RequestParam List<Long> ids){
        try {
            // 检查订单状态，只有草稿状态的订单才能删除
            LambdaQueryWrapper<SalesOrder> checkWrapper = new LambdaQueryWrapper<>();
            checkWrapper.in(SalesOrder::getId, ids);
            checkWrapper.ne(SalesOrder::getStatus, 0); // 不是草稿状态
            long nonDraftCount = salesOrderService.count(checkWrapper);

            if (nonDraftCount > 0) {
                Map<String,Object> resp = new HashMap<>();
                resp.put("success", false);
                resp.put("message", "只能删除草稿状态的订单");
                return resp;
            }

            boolean result = salesOrderService.deleteOrderBatch(ids);
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "订单删除成功" : "订单删除失败");
            resp.put("deletedCount", result ? ids.size() : 0);
            return resp;
        } catch (Exception e) {
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "订单删除失败：" + e.getMessage());
            return resp;
        }
    }

    /** 删除单个订单 */
    @DeleteMapping("/{id}")
    public Map<String,Object> deleteOrder(@PathVariable Long id){
        try {
            // 检查订单状态
            SalesOrder order = salesOrderService.getById(id);
            if (order == null) {
                Map<String,Object> resp = new HashMap<>();
                resp.put("success", false);
                resp.put("message", "订单不存在");
                return resp;
            }

            if (order.getStatus() != 0) {
                Map<String,Object> resp = new HashMap<>();
                resp.put("success", false);
                resp.put("message", "只能删除草稿状态的订单");
                return resp;
            }

            boolean result = salesOrderService.deleteOrderBatch(Arrays.asList(id));
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", result);
            resp.put("message", result ? "订单删除成功" : "订单删除失败");
            return resp;
        } catch (Exception e) {
            Map<String,Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "订单删除失败：" + e.getMessage());
            return resp;
        }
    }

    private String genCode(){
        String ts = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        return "SO"+ts+((int)(Math.random()*90)+10);
    }
}


